package com.zh.mp.demo.config;

import com.zh.mp.demo.filter.MyFilter;
import com.zh.mp.demo.interceptor.MyInterceptor;
import com.zh.mp.demo.interceptor.SessionInterceptor;
import com.zh.mp.demo.listener.MyHttpRequestListener;
import com.zh.mp.demo.listener.MyListener;
import com.zh.mp.demo.listener.SessionListener;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpSessionListener;
import java.util.EventListener;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        InterceptorRegistration interceptorRegistry = registry.addInterceptor(new SessionInterceptor());
        interceptorRegistry.excludePathPatterns("/login");
        interceptorRegistry.excludePathPatterns("/person/token");
        interceptorRegistry.excludePathPatterns("/api/**");
        interceptorRegistry.excludePathPatterns("/sys/**");
        interceptorRegistry.excludePathPatterns("/druid/**");
        interceptorRegistry.addPathPatterns("/**");
    }

    @Bean
    public FilterRegistrationBean<MyFilter> filterRegistrationBean() {
        FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.addUrlPatterns("/api/*");
        filterRegistrationBean.setFilter(myFilter());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.addInitParameter("initParam", "initOk");
        return filterRegistrationBean;
    }

    public MyFilter myFilter() {
        return new MyFilter();
    }


    @Bean
    public ServletListenerRegistrationBean<MyHttpRequestListener> listenerRegistrationBean() {
        ServletListenerRegistrationBean<MyHttpRequestListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
        //servletListenerRegistrationBean.setListener(myListener());
        //servletListenerRegistrationBean.setListener(myHttpRequestListener());
        servletListenerRegistrationBean.setListener(myHttpRequestListener());
        return servletListenerRegistrationBean;
    }

    public MyListener myListener() {
        return new MyListener();
    }

    public MyHttpRequestListener myHttpRequestListener() {
        return new MyHttpRequestListener();
    }

    public SessionListener sessionListener() {
        return new SessionListener();
    }
}
